package admin.data;

import java.util.Collections;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import models.RoleModel;


import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;

public class RoleData {
	private Objectify ofy;
	
	private Cache cache = null;
	
	private String prefix = "role_";
	
	public RoleData() {
		try {
			ObjectifyService.register(RoleModel.class);
		} catch (Exception e) {
			//e.printStackTrace();
		}
		
		try {
            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
           //e.printStackTrace();
        }
		
        ObjectifyOpts opts = new ObjectifyOpts().setSessionCache(true);
		ofy = ObjectifyService.begin(opts);
	}
	
	public RoleModel get(String username) {
		RoleModel page = new RoleModel();
		if (cache != null && cache.containsKey(prefix + username)) {
			page = (RoleModel) cache.get(prefix + username);
		} else {
			try {
				page = ofy.get(new Key<RoleModel>(RoleModel.class, username));
				cache.put(prefix + username, page);
			} catch (Exception e) {
				page = null;
			}
		}
		return page;
	}
	
	public void insert(RoleModel role) {
		if (cache != null) {
			cache.put(prefix + role.getUsername(), role);
		}
		ofy.put(role);
	}
	
	public void delete(RoleModel page) {
		if (cache != null && cache.containsKey(prefix + page.getUsername())) {
			cache.remove(prefix + page.getUsername());
		}
		ofy.delete(page);
	}
}
